package com.ligq.h265toupinpush.avmetting

import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface

class MeetingH264Player(val ip: String) {
    private lateinit var mediaCodec: MediaCodec
    fun initPlayer(surface: Surface) {
        try {
            mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
            val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 1080, 1920)
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 30)
            format.setInteger(MediaFormat.KEY_BIT_RATE, 1080 * 1920)
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10)
            mediaCodec.configure(format, surface, null, 0)
            mediaCodec.start()
        } catch (e: Exception) {
            Log.e(TAG, "initPlayer: ", e)
        }
    }

    fun decode(data: ByteArray) {
        try {
            val inIndex = mediaCodec.dequeueInputBuffer(10000)
            if (inIndex >= 0) {
                val inputBuffer = mediaCodec.getInputBuffer(inIndex)
                inputBuffer?.clear()
                inputBuffer?.put(data, 0, data.size)
                mediaCodec.queueInputBuffer(inIndex, 0, data.size, System.currentTimeMillis(), 0)
            }

            val bufferInfo = MediaCodec.BufferInfo()
            var outIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000)
            while (outIndex >= 0) {
                mediaCodec.releaseOutputBuffer(outIndex, true)
                outIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000)
            }

        } catch (e: Exception) {
            Log.e(TAG, "decode: ", e)
        }

    }
}